﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Dynamic;
using System.Reflection;
using System.Collections;

namespace Infrastructure.Services.ServiceProxies
{

    public class AutoServiceProxy<IService> : DynamicObject, IDisposable
        where  IService:class
    {

        protected IService Proxy;




        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {            
            return base.TryGetMember(binder, out result);
        }
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            Type type = typeof(IService);            
            var mtype = type.GetMethod(binder.Name);
            var targs = new ArrayList(args);
            var parameters = mtype.GetParameters();
            for (int i = args.Length; i < parameters.Length ; i++)
            {
                targs.Add(parameters[i].DefaultValue);
            }
            result = mtype.Invoke(Proxy, targs.ToArray());
            return true;           
        }

        public AutoServiceProxy(string configName)            
        {            
            var cf = new ChannelFactory<IService>(configName);            
            Proxy = cf.CreateChannel() as IService;                    
        }
        public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
        {
            return base.TryInvoke(binder, args, out result);
        }
        public override bool TryUnaryOperation(UnaryOperationBinder binder, out object result)
        {
            return base.TryUnaryOperation(binder, out result);
        }
        public void Dispose()
        {
            var target = this.Proxy as ICommunicationObject;
            if (target!= null)
            {                
                target.Close();                
            }          
        }        
    }  
    
}
